import { defineAsyncComponent } from 'vue'
import { createRouter, createWebHashHistory, Router } from 'vue-router'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import navConfig from './nav.config'


const LoadingComponent = {
  template: `<div v-loading="true" style="min-height: 500px; width: 100%;"></div>`,
}
const ErrorComponent = {
  template: `
    <div style="text-align: center;padding: 100px 0;">Loading error. Please refresh the page and try again</div>`,
}
const getAsyncComponent = func => {
  return defineAsyncComponent({
    loader: func,
    delay: 0,
    timeout: 30000,
    errorComponent: ErrorComponent,
    loadingComponent: LoadingComponent,
  })
}


const load = function(path) {
  return getAsyncComponent(() => import(/* webpackChunkName: "changeLogs" */ `../pages/${path}.vue`))
}

const loadDocs = function(path) {
  return getAsyncComponent(() => import(/* webpackChunkName: "DOCS" */ `../docs${path}.md`))
}

const registerRoute = navConfig => {
  const route = []

  const navs = navConfig
  route.push({
    path: `/component`,
    redirect: `/component/installation`,
    component: load('component'),
    children: [],
  })
  navs.forEach(nav => {
    if (nav.href) return
    if (nav.groups) {
      nav.groups.forEach(group => {
        group.list.forEach(nav => {
          addRoute(nav, 0)
        })
      })
    } else if (nav.children) {
      nav.children.forEach(nav => {
        addRoute(nav, 0)
      })
    } else {
      addRoute(nav, 0)
    }
  })
  function addRoute(page, index) {
    const component = page.path === '/changelog'
      ? load('changelog')
      : loadDocs(page.path)
    const child = {
      path: page.path.slice(1),
      meta: {
        title: page.title || page.name,
        description: page.description,
        lang: 'zhen',
      },
      name: 'component-' + (page.title || page.name),
      component: (component as any).default || component,
    }

    route[index].children.push(child)
  }
  return route
}

let route = registerRoute(navConfig)
const indexRoute = {
  path: `/`,
  meta: { lang: 'zhen' },
  name: 'home',
  component: load('index'),
}

// const guide = {
//   path: `/guide`,
//   meta: {},
//   redirect: '/guide/android',
//   name: 'guide',
//   component: load('guide'),
//   children: [
//     {
//       path: 'android',
//       name: 'android',
//       meta: { },
//       component: load('android'),
//     },
//     {
//       path: 'web',
//       name: 'web',
//       meta: { },
//       component: load('web'),
//     },
//   ],
// }

route = route.concat([indexRoute])
const router: Router = createRouter({
  history: createWebHashHistory(),
  routes: route,
})

export default router
